<?php
/**
 * @title 2646. 最小化旅行的价格总和
 * @author start2004
 */

// ini_set("memory_limit", "128M");

// class Solution {
//
//     function find() {
//
//     }
// }

class Solution {
    /**
     * @param Integer $n
     * @param Integer[][] $edges
     * @param Integer[] $price
     * @param Integer[][] $trips
     * @return Integer
     */
    function minimumTotalPrice($n, $edges, $price, $trips) {
        /**
         * @since 2023-12-06
         *      0
         *     /
         *    1
         *   / \
         *  2   3
         *
         * Trip | 路径上节点
         * ---------------------
         * 0->3     0,1,3
         * 2->1     2,1
         * 2->3     2,1,3
         *
         * Node | Price | Cnt | Total Cost
         * ----------------------------------
         *  0       2      1        2
         *  1       2      3        6
         *  2      10      2       20
         *  3       6      2       12
         *
         * Price*Cnt，树变成
         *      2
         *     /
         *    6
         *   / \
         * 20   12
         *
         * 2+6+20+12 = 40
         * 40-1-10-6=23
         *
         * 优先价值最大，4-6-4        错误
         * 优先损失最小，2-6-8-6      错误
         * 排除损失最大，4-6-4-6-4    错误
         * 间隔取值，4-2-2-4         错误
         */

        /**
         * @since 2023-12-06 点到点存在路径的集合
         */
        $pointToPointArray = [];
        foreach ($edges as list($s, $e)){
            $pointToPointArray[$s][$e] = $e;
            $pointToPointArray[$e][$s] = $s;
        }

        /**
         * @since 2023-12-06 旅行可能重复，格式化处理
         */
        $tripArray = [];
        foreach ($trips as list($s, $e)){
            /**
             * @since 2023-12-06 保证$s<=$e
             */
            if($s>$e){
               list($s, $e) = [$e, $s];
            } else {}

            /**
             * @since 2023-12-06 键值
             */
            $key = "{$s}-{$e}";
            if(isset($tripArray[$key])){
                $tripArray[$key][2] += 1;
            } else {
                $tripArray[$key] = [$s, $e, 1];
            }
        }
        // return $tripArray;

        /**
         * @since 2023-12-06 统计所有旅行，每个点出现次数
         */
        $pointCntArray = array_fill(0, $n, 0);

        /**
         * @since 2023-12-06 每次旅行的路径
         */
        $pathArray = [];
        foreach ($tripArray as list($s, $e, $cnt)){
            // echo str_repeat(PHP_EOL, 3), "trip=[{$s}, {$e}]";

            /**
             * @since 2023-12-06 起点终点一致
             */
            if($s == $e){
                $pathArray[] = $s;
            } else {
                /**
                 * @since 2023-12-06 跳出循环
                 */
                $break = false;

                /**
                 * @since 2023-12-06 层次遍历，找到$s到$e的路径
                 */
                $nodeArray = [$s => [$s]];
                $copyPointToPointArray = $pointToPointArray;
                while($nodeArray){
                    /**
                     * @since 2023-12-06 下次层次遍历的点
                     */
                    $nextNodeArray = [];

                    /**
                     * @since 2023-12-06 遍历当层的点
                     */
                    foreach ($nodeArray as $point=>$bfsPathArray){
                        foreach ($copyPointToPointArray[$point] as $nextPoint){
                            /**
                             * @since 2023-12-06 阻止回头路
                             */
                            unset($copyPointToPointArray[$nextPoint][$point]);

                            /**
                             * @since 2023-12-06 更新路径
                             */
                            $newBfsPathArray = array_merge($bfsPathArray, [$nextPoint]);

                            /**
                             * @since 2023-12-06 到达终点$e
                             */
                            if($nextPoint == $e){
                                $pathArray = $newBfsPathArray;

                                $break = true;
                                break;
                            } else {}

                            /**
                             * @since 2023-12-06 下次遍历点
                             */
                            $nextNodeArray[$nextPoint] = $newBfsPathArray;
                        }

                        /**
                         * @since 2023-12-06 跳出循环
                         */
                        if($break){
                            break;
                        } else {}
                    }

                    /**
                     * @since 2023-12-06 跳出循环
                     */
                    if($break){
                        break;
                    } else {}

                    /**
                     * @since 2023-12-06 赋值下次层次遍历的点
                     */
                    $nodeArray = $nextNodeArray;
                }
            }

            /**
             * @since 2023-12-06 统计次数
             */
            // echo ", path=[", implode(",", $pathArray) ,"]";
            foreach ($pathArray as $point){
                $pointCntArray[$point] += $cnt;
            }
        }
        return $pointCntArray;

        /**
         * @since 2023-12-06 减少重复递归
         */
        $this->dpArray = [];

        /**
         * @since 2023-12-06 各个点上状态
         * 0 => 待定
         * 1 => 半价
         * 2 => 全价
         */
        $pointStatus = str_repeat("0", $n);

        /**
         * @since 2023-12-06 获取最小价格总和
         */
        return self::MinCost($pointCntArray, $price, $pointToPointArray, $pointStatus);
    }

    /**
     * @title 返回最小价格总和
     * @author start2004
     * @since 2023-12-06 Created
     *
     * @param array $pointCntArray
     * @param array $price
     * @param array $pointToPointArray
     * @param string $pointStatus
     * @return int
     */
    function MinCost(Array $pointCntArray = [], Array $price = [], Array $pointToPointArray = [], String $pointStatus = ""){
        if(isset($this->dpArray[$pointStatus])){
            return $this->dpArray[$pointStatus];
        } else {}

        /**
         * @since 2023-12-06 空数组
         */
        if(empty($pointCntArray)){
            $this->dpArray[$pointStatus] = 0;
            return 0;
        } elseif(count($pointCntArray) == 1) {
            /**
             * @since 2023-12-06 只有一个点，直接半价
             */
            $point = key($pointCntArray);
            $cnt = $pointCntArray[$point];

            $minCost = ($price[$point]>>1)*$cnt;
            echo "最后一个点，point={$point}, cnt={$cnt}, cost={$minCost}", PHP_EOL;

            /**
             * @return
             */
            $pointStatus[$point] = 1;
            $this->dpArray[$pointStatus] = $minCost;
            return $minCost;
        } else {}

        /**
         * @since 2023-12-06 最小价格总和
         */
        $minCost = PHP_INT_MAX;

        /**
         * @since 2023-12-06 依次尝试每个点
         */
        foreach ($pointCntArray as $point=>$cnt){
            /**
             * @since 2023-12-06 复制点，和状态
             */
            $copyPointCntArray = $pointCntArray;
            unset($copyPointCntArray[$point]);
            $copyPointStatus = $pointStatus;

            /**
             * @since 2023-12-06 point价格不减半
             */
            $copyPointStatus[$point] = "2";
            $cost1 = $price[$point]*$cnt + self::MinCost($copyPointCntArray, $price, $pointToPointArray, $copyPointStatus);
            $minCost = min($minCost, $cost1);

            /**
             * @since 2023-12-06 point价格减半
             */
            $copyPointStatus[$point] = "1";
            $cost2 = ($price[$point]>>1)*$cnt;

            /**
             * @since 2023-12-06 point相邻的点，不能减半
             */
            foreach ($pointToPointArray[$point] as $nextPoint){
                if(isset($copyPointCntArray[$nextPoint])){
                    /**
                     * @since 2023-12-06 point相邻的点，全价
                     */
                    echo "next, point={$nextPoint}, price=", $price[$nextPoint], ", cnt=", $copyPointCntArray[$nextPoint] ,", cost=", $price[$nextPoint]*$copyPointCntArray[$nextPoint], PHP_EOL;
                    $cost2 += $price[$nextPoint] * $copyPointCntArray[$nextPoint];
                    $copyPointStatus[$nextPoint] = "2";

                    /**
                     * @since 2023-12-06 去掉nextPoint
                     */
                    unset($copyPointCntArray[$nextPoint]);
                } else {}
            }

            /**
             * @since 2023-12-06 point价格减半，计算总价格
             */
            $cost2 += self::MinCost($copyPointCntArray, $price, $pointToPointArray, $copyPointStatus);
            $minCost = min($minCost, $cost2);

            echo "point={$point}, cnt={$cnt}，全价{$cost1}，半价{$cost2}", PHP_EOL;
            foreach ($pointCntArray as $p=>$c){
                echo "[{$p},{$c}], ";
            }
            echo PHP_EOL;
        }

        /**
         * @return
         */
        $this->dpArray[$pointStatus] = $minCost;
        return $minCost;
    }
}

/**
 * @url http://127.0.0.1/leetcode/202312/2023.12.06.php
 */
$datas = [
    // [4, [[0,1],[1,2],[1,3]], [2,2,10,6], [[0,3],[2,1],[2,3]]], // 23
    // [4, [[0,1],[1,2],[1,3]], [2,2,10,6], [[0,3],[2,1],[2,3],[0,1]]], //
    // [2, [[0,1]], [2,2], [[0,0]]], // 1
    [5, [[1,2],[2,0],[0,3],[3,4]], [12,26,22,12,2], [[3,3],[3,2],[3,0],[3,4],[1,1],[2,2],[4,0],[0,2],[2,3],[2,1],[4,2],[0,1],[4,2],[0,4],[0,3],[4,0],[4,0],[3,3],[4,3],[2,2],[4,2],[1,4],[3,2],[4,4],[4,2],[2,3],[4,3],[4,4],[4,2],[0,4],[4,2],[3,4],[4,0],[3,2],[3,1],[2,0],[0,4],[3,4],[2,0],[1,4],[4,2],[4,4],[2,1],[0,1],[4,1],[3,4],[0,4],[2,0],[2,0],[3,3],[4,4],[0,1],[0,1],[0,1],[2,0],[0,1],[3,1],[3,4],[3,4],[4,2],[0,4],[4,4],[3,2],[2,1],[3,2],[1,4],[1,0],[4,2],[4,3],[3,1],[4,4],[3,1],[1,0],[0,0],[0,0],[3,0],[0,2],[2,2],[3,3],[0,3]]], // 2037
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    if(count($data) <= 20){
        var_dump($data);
    } else {
        var_dump(count($data));
    }

    $obj = new Solution();
    $result = $obj->minimumTotalPrice(...$data);
    // $result = $obj->($xhprof->tree($data));
    // $result = $obj->($xhprof->listNode($data));
    // $result = $obj->find(...$data);
    var_dump($result);
    // if(count($result)<=20){
    //     var_dump($result);
    // } else {
    //     var_dump(count($result));
    // }
    echo str_repeat(PHP_EOL, 3);
    echo str_repeat("<br>", 3);
}

// foreach ($datas as $data){
//     $obj = new $data[0][0](...$data[1][0]);
//
//     for ($i=1; $i<count($data[0]); $i++){
//         $func = $data[0][$i];
//         $param = $data[1][$i];
//         $result = $obj->$func(...$param);
//
//         echo $data[0][$i] ."(\"". implode(",", $data[1][$i]) ."\") ";
//             if($result === true){
//                 echo "True";
//             } elseif($result === false) {
//                 echo "False";
//             } elseif($result === null) {
//                 echo "Null";
//             } elseif(is_array($result)) {
//                 var_dump($result);
//             } else {
//                 echo $result;
//             }
//         echo PHP_EOL;
//     }
//
//     echo str_repeat(PHP_EOL, 3);
// }
$xhprof->end();
